package com.xapp.yhjsBirdge;

import android.graphics.Bitmap;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;

/**
 * Created by YH_CK on 2017-12-18.
 */

public class BridgeWebViewClient extends WebViewClient {
    private BridgeWebView webView;

    public BridgeWebViewClient(BridgeWebView webView) {
        this.webView = webView;
    }

    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException var4) {
            var4.printStackTrace();
        }
        if (url.startsWith("yy://return/")) { // native调用h5，h5返回的消息数据
            this.webView.handlerReturnData(url);
            return true;
        } else if (url.startsWith("yy://")) { // 直接接收h5调用，收到后调h5获取消息列表
            this.webView.flushMessageQueue();
            return true;
        } else {
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
    }

    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        if ("WebViewJavascriptBridge.js" != null) {
            //2018.03.27:JS 注入为兼容React在Andoroid 6.0以下版本，有移动端改为前端页面。
            BridgeUtil.webViewLoadLocalJs(view, "WebViewJavascriptBridge.js");
        }

        if (this.webView.getStartupMessage() != null) {
            Iterator var3 = this.webView.getStartupMessage().iterator();

            while (var3.hasNext()) {
                Message m = (Message) var3.next();
                this.webView.dispatchMessage(m);
            }

            this.webView.setStartupMessage((List) null);
        }

    }

    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
    }
}
